package com.example.flutter_book_store;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.idlefish.flutterboost.containers.BoostFlutterActivity;

import java.util.HashMap;
import java.util.Map;

public class PageRouter {
    public static final String NATIVE_PAGE_URL = "sample://nativePage";
    public static final String FLUTTER_PAGE_URL = "sample://flutterPage";
    public static final String TEST_PAGE_URL = "sample://testPage";

    public final static Map<String, String> pageName = new HashMap() {{
        put(FLUTTER_PAGE_URL, "flutterPage");
        put(TEST_PAGE_URL, "testPage");
    }};

    public static boolean openPageByUrl(Context context, String url, Map params) {
        return openPageByUrl(context, url, params, 0);
    }

    public static boolean openPageByUrl(Context context, String url, Map params, int requestCode) {
        String path = url.split("\\?")[0];
        Log.i("openPageByUrl",path);
        try {
            if (pageName.containsKey(path)) {
                Intent intent = BoostFlutterActivity.withNewEngine().url(pageName.get(path)).params(params)
                        .backgroundMode(BoostFlutterActivity.BackgroundMode.opaque).build(context);
                if(context instanceof Activity){
                    Activity activity=(Activity)context;
                    activity.startActivityForResult(intent,requestCode);
                }else{
                    context.startActivity(intent);
                }
                return true;
            }  else if (url.startsWith(NATIVE_PAGE_URL)) {
                Intent intent = new Intent(context, NativePageActivity.class);
                Map<String,Object> map= (Map<String,Object>)params.get("query");
                intent.putExtra("url", (String) map.get("aaa"));
                context.startActivity(intent);
                return true;
            }
            return false;

        } catch (Throwable t) {
            return false;
        }
    }
}
